package cn.itlight.user.service.impl;

import cn.itlight.basic.constant.BaseConstants;
import cn.itlight.basic.exception.BusinessException;
import cn.itlight.basic.utils.MD5Utils;
import cn.itlight.basic.utils.StrUtils;
import cn.itlight.basic.vo.EmailRegisterVo;
import cn.itlight.basic.vo.RegisterVo;
import cn.itlight.org.domain.Employee;
import cn.itlight.user.domain.Logininfo;
import cn.itlight.user.domain.User;
import cn.itlight.user.mapper.LogininfoMapper;
import cn.itlight.user.mapper.UserMapper;
import cn.itlight.user.service.IUserService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-06
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void registerPhone(RegisterVo registerVo) {
        // 把参数都拿出来
        String phone = registerVo.getPhone();
        String password = registerVo.getPassword();
        String confirmPassword = registerVo.getConfirmPassword();
        String smsCodeValue = registerVo.getSmsCodeValue();

        // 1.为空校验
        String phoneCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 2.验证手机号是否一致，验证码是否过期
        if (phoneCodeValueRedis == null){
            throw new BusinessException("验证码已失效，请重试！");
        }
        // 3.判断验证码是否正确
        String split = phoneCodeValueRedis.toString().split(":")[1];
        if (!split.equalsIgnoreCase(smsCodeValue)){
            throw new BusinessException("验证码错误，请重试！");
        }
        // 4.两次密码是否一致
        if (!password.equals(confirmPassword)){
            throw new BusinessException("两次密码不一致");
        }

        // 5.是否注册
        User user = userMapper.loadByPhone(phone);
        if (user != null){
            throw new BusinessException("此用户已经存在，请直接登录！");
        }

        // 6.保存到user
        user = smsCodeDto2User(registerVo);
        userMapper.save(user);

        // 7.保存到logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        // 8.修改user
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);
    }
    @Override
    public void registerEmail(EmailRegisterVo emailRegisterVo) {
        // 把参数都拿出来
        String email = emailRegisterVo.getEmail();
        String smsCodeValueEmail = emailRegisterVo.getSmsCodeValueEmail();
        String passwordEmail = emailRegisterVo.getPasswordEmail();
        String confirmPasswordEmail = emailRegisterVo.getConfirmPasswordEmail();
        if (StringUtils.isEmpty(email)
                || StringUtils.isEmpty(smsCodeValueEmail)
                || StringUtils.isEmpty(passwordEmail)
                || StringUtils.isEmpty(confirmPasswordEmail) ){
            throw new BusinessException("参数为空，请重试！");
        }
        // 1.为空校验
        String emailCodeKey = BaseConstants.VerifyCodeConstant.BUSINESS_REGISTER_PREFIX + email;
        Object emailCodeValueRedis = redisTemplate.opsForValue().get(emailCodeKey);
        // 2.验证邮箱是否一致，验证码是否过期
        if (emailCodeValueRedis == null){
            throw new BusinessException("验证码已失效，请重试！");
        }
        // 3.判断验证码是否正确
        String split = emailCodeValueRedis.toString().split(":")[1];
        if (!split.equalsIgnoreCase(smsCodeValueEmail)){
            throw new BusinessException("验证码错误，请重试！");
        }
        // 4.两次密码是否一致
        if (!passwordEmail.equals(confirmPasswordEmail)){
            throw new BusinessException("两次密码不一致");
        }

        // 5.是否注册
        User user = userMapper.loadByEmail(email);
        if (user != null){
            throw new BusinessException("此用户已经存在，请直接登录！");
        }

        // 6.保存到user
        user = emailCodeDto2User(emailRegisterVo);
        userMapper.save(user);

        // 7.保存到logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);

        // 8.修改user
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);
    }

    @Override
    public User loadByLogininfoId(Long logininfoId) {
        return userMapper.loadByLogininfoId(logininfoId);
    }


    @Override
    public void update(User user) {
        // 1.初始化emplpyee，并保存，这是引用传递
        initUser(user);
        userMapper.update(user);
        // 2.初始化logininfo，并保存
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        Long id = logininfo.getId();
        logininfo = user2Logininfo(user);
        logininfo.setId(id);
        System.out.println(logininfo);
        logininfoMapper.update(logininfo);
    }

    @Override
    public void remove(Long id) {
        User user = userMapper.loadById(id);
        userMapper.remove(id);
        logininfoMapper.remove(user.getLogininfoId());
    }

    private void initUser(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + user.getPassword());
        user.setPassword(saltPassword);
        user.setSalt(salt);
    }
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User smsCodeDto2User(RegisterVo registerVo) {
        String phone = registerVo.getPhone();
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + registerVo.getPassword());
        user.setPassword(saltPassword);
        user.setSalt(salt);
        return user;
    }

    private User emailCodeDto2User(EmailRegisterVo emailRegisterVo) {
        String email = emailRegisterVo.getEmail();
        User user = new User();
        user.setUsername(email);
        user.setEmail(email);
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + emailRegisterVo.getPasswordEmail());
        user.setPassword(saltPassword);
        user.setSalt(salt);
        return user;
    }
}
